package cn.edu.jxau.test;

/**
 * 判断单链表是否有环
 * 
 * @author Fudashi
 */
public class Main {

	public static void main(String[] args) {

		Node node1 = new Node(1);
		Node node2 = new Node(2);
		Node node3 = new Node(3);
		Node node4 = new Node(4);
		Node node5 = new Node(5);
		Node node6 = new Node(6);
		node1.next = node2;
		node2.next = node3;
		node3.next = node4;
		node4.next = node5;
		node5.next = node6;
		node5.next = node4;
		System.out.println(hasCircle(node1));
	}

	public static boolean hasCircle(Node first) {

		Node slow = first;
		Node fast = first;
		while (fast != null && fast.next != null) {
			fast = fast.next.next;
			slow = slow.next;
			if (fast == slow) {
				break;
			}
		}
		return fast != null && fast.next != null;
	}
}

class Node {

	public int data;
	public Node next;

	public Node(int data) {
		this.data = data;
	}
}